package mq

import (
	"charging_pile/util/protocol/jiuxing"
	"context"
	"fmt"
	"math"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

func handle01(nc *natsClient, in *jiuxing.Package) (jxMsg *jiuxing.Package) {
	msg := jiuxing.Msg01{}
	msg.Decode(in.Payload)
	logx.Infof("msg01:%+v", msg)

	resp := jiuxing.Msg02{}
	defer func() {
		logx.Infof("msg:%+v", resp)
	}()

	defer func() {
		jxMsg = &jiuxing.Package{
			Cmd:        2,
			Sn:         in.Sn,
			Encryption: in.Encryption,
			PackageLen: 0,
			Payload:    []uint8{},
			Check:      0,
		}

		jxMsg.Payload = resp.Encode()
		jxMsg.PackageLen = uint16(len(jxMsg.Payload))
	}()

	resp.Tm = formatJxTime()
	resp.Result = 1
	resp.Reason = 0
	// 校验时间
	if math.Abs(float64(time.Now().Unix()-jiuxing.GetTimeStamp(msg.Tm))) > 600 {
		logx.Info("time is over 600s", time.Now().Unix(), jiuxing.GetTimeStamp(msg.Tm))
		resp.Result = 2
		resp.Reason = 6
		return
	}
	//查询充电桩是否合法
	logx.Info("pile sn:", jiuxing.GetBcdString(in.Sn))
	fmt.Println(jiuxing.GetBcdString(in.Sn))
	pile, err := nc.SvcCtx.Modes.ChargePile.FindOneBySn(context.Background(), jiuxing.GetBcdString(in.Sn))
	if err != nil {
		logx.Info("pile not found db err")
		resp.Result = 2
		resp.Reason = 5
		return
	}

	if pile == nil {
		resp.Result = 2
		resp.Reason = 5
		return
	}

	if pile != nil && pile.Status != 0 {
		resp.Result = 2
		resp.Reason = 4
		return
	}
	//充电桩合法
	if resp.Result == 1 {
		resp.QRPrefix = []byte(fmt.Sprintf("yaoyao.ziee.wang/pile/startCharge?sn=%s&", pile.Sn))
		resp.QRNum = byte(pile.PlugNum)
		for i := 0; i < int(pile.PlugNum); i++ {
			resp.QRList = append(resp.QRList, []byte(fmt.Sprintf("plug=%d", i)))
		}
	}
	return
}

func init() {
	HandlerMap[uint8(1)] = handle01
}
